package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BusinessException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    public Result<String> exceptionHandler(BusinessException businessException){
        return Result.error(businessException.getMessage());
    }
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException sqlIntegrityConstraintViolationException){
        log.info("异常信息是:{}",sqlIntegrityConstraintViolationException.getMessage());
        //获取异常信息
        String message = sqlIntegrityConstraintViolationException.getMessage();
        // 将异常信息进行分割
        if (message.contains("Duplicate entry")) {
            String[] s = message.split(" ");
            String username=s[2];
            return Result.error(username+MessageConstant.NAME_HAS_EXIST);
        }else {
            return Result.error(MessageConstant.UN_KNOW_ERROR);
        }
    }
}
